package com.fkorotkov.gradle.libraries;

import com.fkorotkov.gradle.libraries.tasks.SyncLibrariesTask;
import com.fkorotkov.gradle.libraries.tasks.UpdateLibrariesTask;

import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;

import java.io.File;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class LibrariesPlugin implements Plugin<Project> {
  // to make sure there is one manager per root project to not re-parse json over and over again
  private static volatile ConcurrentHashMap<Project, LibrariesManager> librariesManagers = new ConcurrentHashMap<>();

  @Override
  public void apply(Project project) {
    project.getExtensions().add("libraries", getManager(project.getRootProject()));
    if (project == project.getRootProject()) {
      project.getTasks().create("syncLibraries", SyncLibrariesTask.class);
      project.getTasks().create("updateLibraries", UpdateLibrariesTask.class);
    }
    project.afterEvaluate(new Action<Project>() {
      @Override
      public void execute(Project pp) {
        pp.getConfigurations().all(new Action<Configuration>() {
          @Override
          public void execute(Configuration configuration) {
            String name = configuration.getName();
            if (name == "implementation" || name == "compile") {
              Iterator<Dependency> ret = configuration.getDependencies().iterator();
//              System.err.println("this configuration is " + ret.hasNext());
              while (ret.hasNext()) {
                Dependency item = ret.next();
                System.err.println("this configuration is " + item.getName());
              }
            }

          }
        });
      }
    });
    /*project.getConfigurations().all(new Action<Configuration>() {
      @Override
      public void execute(Configuration configuration) {
        String name = configuration.getName();
        if (name != "implementation" && name != "compile") {
          return;
        } else {
        }
        Iterator<Dependency> ret = configuration.getDependencies().iterator();
        System.err.println("this configuration is " + ret.hasNext());
        while (ret.hasNext()) {
          Dependency item = ret.next();
          System.err.println("this configuration is " + item.getName());
        }

        //为Project加入Gson依赖
//        configuration.getDependencies().add(project.getDependencies().create("com.github.szhittech:ikecinslinksdk:0.0.0-SNAPSHOT"));
      }
    });*/


  }

  private static LibrariesManager getManager(Project project) {
    File dependenciesFile = new File(project.getRootDir(), "dependencies.json");
    librariesManagers.putIfAbsent(project, new LibrariesManager(project, dependenciesFile));
    return librariesManagers.get(project);
  }
}
